//@Time:2022/4/3 0:56
//@Author:aFun

package indi.csms_springboot.controller;

import com.mysql.jdbc.log.Log;
import indi.csms_springboot.domain.User;
import indi.csms_springboot.service.LoginService;
import indi.csms_springboot.service.impl.LoginServiceImpl;
import indi.csms_springboot.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.apache.commons.beanutils.BeanUtils;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.Random;

@Controller
public class LoginController {

    @Autowired
    LoginService loginService;

    @RequestMapping("/checkCode")
    public void checkCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //服务器通知浏览器不要缓存
        response.setHeader("pragma", "no-cache");
        response.setHeader("cache-control", "no-cache");
        response.setHeader("expires", "0");

        //在内存中创建一个长80，宽30的图片，默认黑色背景
        //参数一：长
        //参数二：宽
        //参数三：颜色
        int width = 80;
        int height = 30;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //获取画笔
        Graphics g = image.getGraphics();
        //设置画笔颜色为灰色
        g.setColor(Color.GRAY);
        //填充图片
        g.fillRect(0, 0, width, height);

        //产生4个随机验证码，12Ey
        String checkCode = getCheckCode();
        //将验证码放入HttpSession中
        request.getSession().setAttribute("CHECKCODE_SERVER", checkCode);

        //设置画笔颜色为黄色
        g.setColor(Color.YELLOW);
        //设置字体的小大
        g.setFont(new Font("黑体", Font.BOLD, 24));
        //向图片上写入验证码
        g.drawString(checkCode, 15, 25);

        //将内存中的图片输出到浏览器
        //参数一：图片对象
        //参数二：图片的格式，如PNG,JPG,GIF
        //参数三：图片输出到哪里去
        ImageIO.write(image, "PNG", response.getOutputStream());
    }
    /**
     * 产生4位随机字符串
     */
    private String getCheckCode() {
        String base = "0123456789ABCDEFGabcdefg";
        int size = base.length();
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 1; i <= 4; i++) {
            //产生0到size-1的随机值
            int index = r.nextInt(size);
            //在base字符串中获取下标为index的字符
            char c = base.charAt(index);
            //将c放入到StringBuffer中去
            sb.append(c);
        }
        return sb.toString();
    }

    @RequestMapping("/logining")
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        ModelAndView modelAndView = new ModelAndView();
        // 设置编码
        request.setCharacterEncoding("utf-8");
        // 获取数据
        String verifycode = request.getParameter("verifycode");
        // 验证码校验
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");                // 防止验证码在返回页面中出现被缓存以致不更新的情况

        // 验证码验证应在后面完成阶段进行验证
        if (!checkcode_server.equalsIgnoreCase(verifycode)) {
            modelAndView.addObject("login_msg", "验证码错误！");
            modelAndView.setViewName("login");
            System.out.println(modelAndView);
            return modelAndView;
        }

        // 封装USER对象
        Map<String, String[]> map = request.getParameterMap();

        User user = new User();
        try {
            BeanUtils.populate(user, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


        R loginR = loginService.login(user);
        if (loginR.getFlag()) {
            User loginUser= (User) loginR.getData();
            // 登录成功
            session.setAttribute("user", loginUser);
            R r = loginService.stragyMethodForRole(loginUser);
            if(r.getFlag()){
                String loginPath= (String) r.getData();
                modelAndView.setViewName(loginPath);
                return modelAndView;
            }else{
                modelAndView.addObject("login_msg", "数据库异常！");
                modelAndView.setViewName("login");
                return modelAndView;
            }
        } else {
            // 登录失败
            modelAndView.addObject("login_msg", "用户名或密码错误！");
            modelAndView.setViewName("login");
            return modelAndView;
        }

//        User user=new User();
//        user.setAccount("aFun@qq.com");
//        user.setPassword("ICy5YqxZB1uWSwcVLSNLcA==");
//        user.setUid(1);
//        request.getSession().setAttribute("user",user);
//        modelAndView.setViewName("managerIndex");
//        return modelAndView;

//        User teacher=new User();
//        teacher.setAccount("teacher01@163.com");
//        teacher.setPassword("4QrcOUm6Wau+VuBX8g+IPg==");
//        teacher.setUid(30001);
//        request.getSession().setAttribute("user",teacher);
//        modelAndView.setViewName("teacherIndex");
//        return modelAndView;

//        User student=new User();
//        student.setAccount("student01@163.com");
//        student.setPassword("4QrcOUm6Wau+VuBX8g+IPg==");
//        student.setUid(40001);
//        request.getSession().setAttribute("user",student);
//        modelAndView.setViewName("studentIndex");
//        return modelAndView;

    }


    @RequestMapping("alterPwd")
    public ModelAndView alterPwd(HttpServletRequest request) throws UnsupportedEncodingException {
        ModelAndView modelAndView=new ModelAndView();

        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        Map<String, String[]> map = request.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        String oldPassword = map.get("oldPassword")[0];
        R r = loginService.alterPassword(user,oldPassword);

        if (r.getFlag()) {
            // 修改成功
            session.removeAttribute("user");            // 修改密码成功后应使用户重新登录
            request.setAttribute("alter_msg", "修改成功，正在回到登录界面");
            // 休眠1000毫秒
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            modelAndView.setViewName("login");
            return modelAndView;
        } else {
            // 修改失败
            request.setAttribute("alter_msg", r.getMsg());
            modelAndView.setViewName("alterPwd");
            return modelAndView;
        }
    }

}
